package com.hd.crdao.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hd.crdao.R;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.GlobalData;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.NotificationsUtils;
import com.hd.crdao.utils.QRCode;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.io.FileOutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/8/17 0017
 */

public class CodePayActivity extends BaseActivity {
    @BindView(R.id.code_pay_head)
    ExpandHeadView mCodePayHead;
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.iv_payCode)
    ImageView mIvPayCode;
    @BindView(R.id.setMoney)
    TextView mSetMoney;
    @BindView(R.id.notifyTip)
    TextView mNotifyTip;
    @BindView(R.id.saveQCode)
    TextView mSaveQCode;
    @BindView(R.id.saveArea)
    LinearLayout mSaveArea;
    public MyPayResultReceiver mMyPayResultReceiver;
    public String mOrderPrice;



    @Override
    protected int getLayoutId() {
        return R.layout.activity_code_pay;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.setPriority(1000);
        intentFilter.addAction(JPushInterface.ACTION_NOTIFICATION_RECEIVED);
        intentFilter.addAction(JPushInterface.ACTION_REGISTRATION_ID);
        intentFilter.addAction(JPushInterface.ACTION_MESSAGE_RECEIVED);
        intentFilter.addAction(JPushInterface.EXTRA_NOTIFICATION_ID);
        intentFilter.addAction(JPushInterface.ACTION_NOTIFICATION_OPENED);
        intentFilter.addCategory(getPackageName());
        mMyPayResultReceiver = new MyPayResultReceiver();

        registerReceiver(mMyPayResultReceiver, intentFilter);


    }

    @Override
    protected void initData() {
        String businessId = SPUtils.getString(Config.businessId, "");
        String userId = SPUtils.getString(Config.userId, "");
        mOrderPrice = getIntent().getStringExtra("orderPrice");
        String mProductId = getIntent().getStringExtra("productId");
        ALog.d(mProductId + "----" + mOrderPrice);
        String T0Flag = getIntent().getStringExtra("T0Flag");
        mTvMoney.setText("￥" + mOrderPrice + "元");
        if (NotificationsUtils.isNotificationEnabled(UIUtils.getContext())) {
            mNotifyTip.setVisibility(View.GONE);
        } else {
            mNotifyTip.setVisibility(View.VISIBLE);
        }
        loadData(businessId, userId, mOrderPrice, mProductId, T0Flag);

    }


    @Override
    protected void initListener() {
        mCodePayHead.getLeftArrowLL().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCodePayHead.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UIUtils.getContext(), AccountDetailsActivity.class));
            }
        });
    }


    /**
     * 加载数据
     *
     * @param businessId
     * @param userId
     * @param orderPrice
     * @param productId
     * @param T0Flag
     */
    private void loadData(String businessId, String userId, String orderPrice, String productId, String T0Flag) {
        OkHttpUtils.post().url(Constants.CIBWXPAYCODE_URL)
                .addParams("carBusinessId", businessId)
                .addParams("userId", userId)
                .addParams("orderPrice", orderPrice)
                .addParams("productId", productId)
                .addParams("T0Flag", T0Flag)
                .addParams("sign", Constants.SIGN).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show("网络开了个小差");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String success = (String) json.get("success");
                            String message = (String) json.get("message");
                            if (TextUtils.equals("00", success)) {
                                String codeUrl = (String) json.get("codeUrl");
                                mIvPayCode.setImageBitmap(QRCode.createQRCodeWithLogo6(codeUrl, 500,
                                        BitmapFactory.decodeResource(UIUtils.getResources(), R.drawable.xingye_erwei_2x)));
                            } else {
                                MyToast.show(message);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMyPayResultReceiver);
    }


    @OnClick({R.id.setMoney, R.id.saveQCode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setMoney:
                finish();
                break;
            case R.id.saveQCode:
                saveQcode();
                break;
        }
    }


    /**
     * 保存二维码的方法
     */
    private void saveQcode() {
        Bitmap bitmap = DragBitmap();
        String fileName = GlobalData.SystemPhotoPath + "/" + System.currentTimeMillis() + ".jpg";
        ALog.d(fileName);
        try {
            FileOutputStream fos = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            ALog.d("照片已保存到：" + fileName);
            MyToast.show("照片已保存到：" + fileName);
        } catch (Exception e) {
            ALog.d(e.getMessage());
        }

    }

    private Bitmap DragBitmap() {
        Bitmap bitmap = Bitmap.createBitmap(UIUtils.dip2Px(355), UIUtils.dip2Px(400), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint p = new Paint();
        p.setTextSize(UIUtils.dip2Px(20));
        p.setColor(getResources().getColor(R.color.colorAppMain));
        p.setStyle(Paint.Style.FILL);//设置填满

        canvas.drawRect(0, 0, UIUtils.dip2Px(356), UIUtils.dip2Px(400), p);// 长方形
        p.reset();
        p.setColor(Color.WHITE);
        p.setAntiAlias(true);
        p.setFlags(Paint.ANTI_ALIAS_FLAG);
        p.setTextSize(UIUtils.dip2Px(14));
        p.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("无需加好友,扫描二维码向我付钱", UIUtils.dip2Px(178), UIUtils.dip2Px(35), p);
        //p.reset();
        p.setTextSize(UIUtils.dip2Px(30));
        canvas.drawText("￥"+
                mOrderPrice, UIUtils.dip2Px(178), UIUtils.dip2Px(80), p);

        p.reset();
         mIvPayCode.buildDrawingCache();
        Bitmap drawingCache = mIvPayCode.getDrawingCache();
        canvas.drawBitmap(drawingCache, UIUtils.dip2Px(178)-drawingCache.getWidth()/2, UIUtils.dip2Px(120), p);

        return bitmap;
    }


    public class MyPayResultReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            ALog.d(action);

            if (TextUtils.equals(JPushInterface.ACTION_NOTIFICATION_RECEIVED, action)) {
                ALog.d("验证成功");
                MyToast.show("付款成功");
                Bundle bundle = intent.getExtras();
                String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
                String message = bundle.getString(JPushInterface.EXTRA_ALERT);
                ALog.d(" title : " + title);
                ALog.d("message : " + message);
                if (!TextUtils.isEmpty(message) && message.contains("订单号") && message.contains(mOrderPrice)) {
                    showDialog(CodePayActivity.this);
                }

            }
        }

        private void showDialog(Context context) {
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_paysuccess);
            Button mMakeSure = (Button) dialog.findViewById(R.id.makesure);

            dialog.show();
            mMakeSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }

    }

}
